package com.huluobo.hyj.hyjmodel.contract.Chat

import com.huluobo.hyj.hyjmodel.adapter.EMCallbackAdapter
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage

/**
 *@author : USER
 *@date : 2020/9/17 17:11
 *@params :消息协议层
 *@description:
 */
class ChatPresenter(val view:ChatContract.View) :ChatContract.Presenter {
    val messages = mutableListOf<EMMessage>() //EMMessage就是构建的一条条的消息
    //发送消息的方法
    override fun sendMessage(contact: String, message: String) {
        //发送消息的model 构建一条消息
        val createMessage = EMMessage.createTxtSendMessage(message, contact)
        createMessage.setMessageStatusCallback(object :EMCallbackAdapter(){
            override fun onSuccess() {
                super.onSuccess()
                runOnUiThread { view.onSendMessageSuccess() }
            }

            override fun onError(code: Int, error: String?) {
                super.onError(code, error)
                runOnUiThread { view.onSendMessageFailed() }
            }
        })
        messages.add(createMessage)
        view.onStartSendMessage()
        EMClient.getInstance().chatManager().sendMessage(createMessage)//真正的发送消息
    }
    //将消息加入当前的消息列表里
    override fun addMessage(username: String, message: MutableList<EMMessage>) {
        message?.let { this.messages.addAll(it) }
        //更新消息为已读消息
        //获取跟联系人的会话，然后标记会话里面的消息全部为已读
        val conversation = EMClient.getInstance().chatManager().getConversation(username)
        conversation.markAllMessagesAsRead()//标记为已读
    }
}